import requests

from .constants import BROWSER_USER_AGENT
from .models.device_list_request import DeviceListRequest


class DeviceManager:
    DEVICE_LIST_URL = "https://api-consolepro.onethingcloud.com/v1/device/device_list"
    DEVICE_GENERATE_URL = "https://api-consolepro.onethingcloud.com/v1/device/generate_url"

    DEFAULT_HEADERS = {
        "User-Agent": BROWSER_USER_AGENT,
        "Accept": "application/json, text/plain, */*",
        "Referer": "https://consolepro.onethingcloud.com/",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Origin": "https://consolepro.onethingcloud.com",
        "Content-Type": "application/json"
    }

    DEFAULT_DEVICE_LIST_PARAMS = {
        "page": 1,
        "pageSize": 20,
        "deviceGroup": [],
        "deviceType": [],
        "deviceStatus": [],
        "bizId": [],
        "fuzzyQuery": ""
    }

    def __init__(self, dlr: DeviceListRequest):
        session = requests.session()
        session.headers.update(self.DEFAULT_HEADERS)
        session.cookies.update(dlr.model_dump())
        self.session = session

    def device_list(self, **kwargs):
        params = self.DEFAULT_DEVICE_LIST_PARAMS.copy()
        for key, value in kwargs.items():
            if value is not None:
                params[key] = value
        response = self.session.post(self.DEVICE_LIST_URL, json=params)
        response.raise_for_status()
        return response.json()

    def generate_url(self, sn: str):
        data = dict()
        data["sn"] = sn
        response = self.session.post(self.DEVICE_GENERATE_URL,json=data)
        response.raise_for_status()
        return response.json()
